package com.x.utils;

import cn.hutool.core.codec.Base64;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * the class of advance
 *
 * <p>
 * .
 *
 * @author little_lunatic
 * @date 2024-06-12
 */
//@Data
//@Component
public class JasyptUtils {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;


    public static String encrypt(String data, String key) {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] decryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.encode(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encryptedData, String key) {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedBytes = cipher.doFinal(Base64.decode(encryptedData));
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws Exception {

        String key = "1234567890qwerty1234567890qwerty";
        String root = encrypt("root", key);
        String passwd = encrypt("123456", key);
        System.out.println(root);
        System.out.println(passwd);
        System.out.println(decrypt(root, key));
        System.out.println(decrypt(passwd, key));
    }

//    public static void main(String[] args) {
//        // jar 包里有三种加密方式 AES256TextEncryptor \ BasicTextEncryptor \ StrongTextEncryptor
//        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//        textEncryptor.setPassword("jiamimiyao");
//
//        String userName = textEncryptor.encrypt("root");
//        String passWord = textEncryptor.encrypt("123456");
//
//        System.out.println("userName==="+userName);
//        System.out.println("passWord==="+passWord);
//    }
}
